#include <iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<netinet/in.h>
int main(int argc,char*argv[]){
    if(argc!=3){
        std::cout<<"Usage: "<<argv[0]<<" ip port"<<std::endl;
        return 1;
    }
    std::string ip=argv[1];
    uint16_t port=std::stoi(argv[2]);
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0){
        std::cout<<"create socket error"<<std::endl;
        return 1;
    }
    //客户端不需要显示的bind
    //os会自动分配一个可用端口
    //可以显示的bind，但不建议，因为一个端口只应该绑定一个进程
    //填写服务器信息
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(port);
    server.sin_addr.s_addr=inet_addr(ip.c_str());

    while(true){
        std::string input;
        std::cout<<"input message:";
        std::getline(std::cin,input);
        int n=sendto(sockfd,input.c_str(),input.size(),0,(struct sockaddr*)&server,sizeof(server));
        if(n<0){
            std::cout<<"sendto error"<<std::endl;
            return 1;
        }
        char buffer[1024]={0};
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        memset(&peer,0,sizeof(peer));
        int m=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        buffer[m]='\0';
        std::cout<<buffer<<std::endl;
    }
    return 0;
}